import React, { FC, useEffect, useState } from 'react'
import { getUserSelectList, getConfirmUpdatePrice } from '@/api/prepaidCard'
import { Popup } from 'antd-mobile'
import { useAsyncEffect } from 'ahooks'
import { CourseId } from '@/types'
import { XBusinesslineId } from '@/constants'
import { Product } from '@/types/product'
import { decode, encode } from 'js-base64'
import { useAppDispatch, useAppSelector } from '@/store'
import {
  changePriceParam,
  confirmUpdatePrice,
  selectConfirmUpdatePriceParam,
  selectOrderCoupon,
  updateOrderCoupon,
} from '@/store/confirmPay'
import { ordercouponlist } from '@/api/orderCoupon'
import { CashCoupon, OrderCoupon, OrderCouponInfo } from '@/types/orderCoupon'
interface PrepaidCardProps {
  productInfo: Product[]
  course_id: CourseId
  balance: string | number
  orderCouponInfo: Partial<OrderCouponInfo>
  setVisible: (status: boolean) => void
}
const prepaidCard: FC<PrepaidCardProps> = (props) => {
  // 注：若商品申请退费时讲义已签收，需根据签收的讲义按分类扣除费用。
  const dispatch = useAppDispatch() //
  const [select, setSelect] = useState<string>('')
  const agreestyleStr = 'text-red-E02727 icon-icon_selected'
  /**优惠券信息 */
  const [orderCouponInfo, setOrderCouponInfo] = useState<Partial<OrderCouponInfo>>(
    useAppSelector(selectOrderCoupon),
  )
  const [selectCard, setSelectCard] = useState<CashCoupon>()

  const paramTmp = useAppSelector(selectConfirmUpdatePriceParam)

  const changeCoupon = async (
    chooseUserCoupons: Array<{ category: number; user_coupon_id: string }>,
  ) => {
    const product_info = props.productInfo.map((val) => {
      return {
        product_id: val.productId,
        price: val.price,
      }
    })
    const res = await ordercouponlist({
      app_id: 1,
      product_info: product_info,
      choose_user_coupons: chooseUserCoupons,
      'X-Businessline-Id': XBusinesslineId,
    })
    dispatch(updateOrderCoupon(res.result.data))
    setOrderCouponInfo(res.result.data)
  }
  const product_info = props.productInfo.map((val) => {
    return {
      product_id: val.productId,
      price: val.price,
      product_num: 1,
      brand: val.product_type,
    }
  })
  const changePrise = async (selectCard: CashCoupon) => {
    const param = {
      ...paramTmp,
      product_info: decode(JSON.stringify(product_info)),
      use_gold: '1',
      balance: props.balance.toString(),
      choose_user_coupons: [
        {
          user_coupon_id: selectCard.user_coupon_id,
        },
      ],
      'X-Businessline-Id': XBusinesslineId,
    }
    /**更新价格 */
    const res = await getConfirmUpdatePrice(param)
    dispatch(confirmUpdatePrice(res.result.data))
    dispatch(changePriceParam(param))
  }
  useAsyncEffect(async () => {
    if (selectCard) {
      /**更新价格 */
      changePrise(selectCard)
      /**更新优惠券 */
      changeCoupon([{ category: selectCard.category, user_coupon_id: selectCard.user_coupon_id }])
    } else {
    }
  }, [selectCard])
  // const updatePriseFn = async () => {}
  return (
    <Popup
      visible={true}
      onMaskClick={() => {
        props.setVisible(false)
      }}
      bodyStyle={{ height: '50rem' }}
    >
      <div className=" pl-r1.6 pr-r1.6 ">
        <div className=" text-center text-gray-333333 text-r1.6 leading-r1.6 font-medium font-medium-family relative pl-r1.0 pr-r1.0 pt-r1.6 pb-r2.0">
          <span>优惠券</span>
          <span
            className=" absolute right-0 w-r2.0 h-r2.0 text-r1.6"
            onClick={() => {
              props.setVisible(false)
            }}
          >
            <i className="iconfont icon-icon_colse"></i>
          </span>
        </div>
        <div>
          {orderCouponInfo.cash_coupon_list?.map((val, key) => {
            return (
              <div
                className=" m-r1.6 flex flex-row "
                key={key}
                onClick={() => {
                  setSelectCard(val)
                }}
              >
                <div className=" flex-1.3">
                  <span>¥ {val.discount}</span>
                  <span> {val.threshold_text}</span>
                </div>
                <div className=" flex-1.7">
                  <span> {val.category_desc}</span>
                  <span> {val.coupon_name}</span>
                  <span>
                    {' '}
                    {val.valid_stime} 至{val.valid_etime}{' '}
                  </span>
                  <span>
                    {selectCard?.user_coupon_id === val.user_coupon_id ? (
                      <i className="iconfont icon-icon_selected text-r1.6 "></i>
                    ) : null}
                  </span>
                </div>
              </div>
            )
          })}
        </div>
      </div>
      <div className="w-full fixed bottom-0  h-r8.6  bg-white">
        <div className=" h-r6.0 pl-r1.6 pr-r1.6 pt-r0.9 pb-r1.0 leading-r6.0 overflow-hidden text-center ">
          <span
            className="  text-r1.4 h-r4.0 w-r17.0  text-white leading-r4.0 rounded-r2.0  bg-gradient-to-r from-orange-FF664F to-orange-FF3627  inline-block "
            onClick={() => {
              props.setVisible(false)
            }}
          >
            确定
          </span>
        </div>
      </div>
    </Popup>
  )
}

export default prepaidCard
